import { HTTP_REQUEST_URL, HEADER, TOKENNAME } from '@/config/app';

/**
 * 发送请求
 */
function baseRequest(url, method, data) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;

	// if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
	if (uni.getStorageSync('userInfo').token) header[TOKENNAME] = uni.getStorageSync('userInfo').token;

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/api/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (res.statusCode == 200){
					reslove(res.data, res);
				}else if (res.statusCode == 201){
					reslove(res.data, res);
				}else if (res.statusCode == 401){
					uni.showModal({
					    title: '温馨提示',
					    content: '请登录后操作',
						showCancel: false,
					    success: function (res) {
					        if (res.confirm) {
					            uni.reLaunch({
					            	url:'/pages/user/user'
					            })
					        }
					    }
					});
					reject(res.data);
					// reslove(res.data, res);
				}else if ([410000, 410001, 410002, 40000].indexOf(res.statusCode) !== -1) {
					// toLogin();
					reject(res.data);
				}else if([500, 501, 502, 503, 504, 505].indexOf(res.statusCode) !== -1){
					uni.reLaunch({
						url:'/pages/error/error'
					})
					reject(res.data);
				} else
					reject(res.data.message || '系统错误');
			},
			fail: (message) => {
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;